<?php

namespace app\admin\controller;

use app\admin\model\User;
use think\Controller;
use think\Request;
use think\Session;


class Login extends Controller
{

    /**
     * 退出登录处理
     *Method loginOut
     * @return \think\response\Redirect
     */
    public function loginOut()
    {
        Session(null);

        return redirect('admin/login/login');
    }
    //返回登录页面
    public function login()
    {
        if (session('userInfo') == false) {

            return view('login/login');
        } else {

            $userInfo = session('userInfo');

            $data = User::where('id',$userInfo['id'])->find();

            if ($userInfo['token'] != $data['token']) {

                return redirect(url('admin/login/login'));
            } else {

                User::where('id', $userInfo['id'])->update(['token' => $userInfo['token']]);
                return redirect(url('test512/sign/index'));
            }

        }
    }

    //登录处理
    public function doLogin(Request $request)
    {
        $data = $request->post();
        $data['password'] = md5(md5($data['password']));


        $res = User::where('username', $data['username'])->find();


        if ($res == false) {
            $this->error('账号有误', 'admin/login/login');
        } else {
            if ($res['password'] != $data['password']) {
                $this->error('密码有误', 'admin/login/login');

            }

            $res['token'] = rand().time();//生成token

            User::where('id',$res['id'])->update(['token'=>$res['token']]);

            session('u_id',$res['id']);
            session('userInfo',$res);

            return redirect(url('test512/sign/index'));
        }
    }


}
